package com.example.rabbit.demo.exchange.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @program: rabbit-demo
 * @description:
 * @author: zhaoliang
 * @create: 2019-12-30 14:26
 */
public class ConsumerTopicExchange2 {
    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.200.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.通过connection创建一个channel
        Channel channel = connection.createChannel();
        //4.声明（创建）一个队列
        //参数1：队列名称；参数2：是否持久化；参数3：是否独占；参数4：是否自动删除；参数5：扩展参数
        String exchangeName="test_topic_exchange";
        String exchangeType="topic";
        //先测试user.#，在测试user.*，会同时绑定两个，需要去控制台Exchange先去解绑，才能测试出效果
        //String routingKey="user.#";//#匹配一个或多个词
        String routingKey="user.*";//*匹配一个词
        String queueName = "test_topic_queue02";
        //String queueName = "test_topic_queue01";

        //声明一个交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        //声明一个队列
        channel.queueDeclare(queueName,true,false,false,null);
        //建立一个绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);
        //5.创建一个消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        //6.设置Channel
        channel.basicConsume(queueName,true,queueingConsumer);
        //7.获取消息
        while (true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("Consumer消费的消息："+msg);
            //Envelope envelope = delivery.getEnvelope();
        }

    }
}
